﻿Option Explicit On
'*******************************************************************
' Program: pkgVisio
' Author: Albert E Edlund
' Date:
'
' Purpose:
' Working with office object XML
'
'*******************************************************************


#Region " imports "

Imports System
Imports System.Object
Imports System.IO
Imports System.IO.TextReader
' need to reference windowsbase in .net
Imports System.IO.Packaging

' need for dbconnectionstringbuilder used in clsConnections
Imports System.Data.Common

Imports System.Windows
Imports System.Windows.Forms
Imports System.Text.StringBuilder

Imports Microsoft.VisualBasic

Imports System.Text
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

Imports System.Xml
Imports System.Linq
Imports System.Linq.Enumerable
Imports System.Windows.Input

Imports System.Xml.Serialization
Imports System.Xml.Linq
Imports System.Xml.XPath

Imports ADODB
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Sql


Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging


' visio v15 does not use a xName prefix which may put it into conflict with other open office apps
Imports <xmlns="http://schemas.microsoft.com/office/visio/2012/main">
Imports <xmlns:rs="urn:schemas-microsoft-com:rowset">

' generic namespace for office open xml, used in all of them
Imports <xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">

Imports pkgVisio
Imports pkgVisio.clsStructures



#End Region



'**********************************************************************************
'
'**********************************************************************************
'
Public Class clsDocument



#Region " test strings "


    Public Const customXML As String = "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes"" ?>  " _
        & "<Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"" " _
        & "xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes""> " _
        & "<property fmtid=""{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"" pid=""2"" name=""_VPID_ALTERNATENAMES""> " _
        & "<vt:lpwstr/> " _
        & "</property> " _
        & "<property fmtid=""{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"" pid=""3"" name=""BuildNumberCreated""> " _
        & "<vt:i4>1007291932</vt:i4> " _
        & "</property> " _
        & "<property fmtid=""{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"" pid=""4"" name=""BuildNumberEdited""> " _
        & "<vt:i4>1007291932</vt:i4> " _
        & "</property> " _
        & "<property fmtid=""{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"" pid=""5"" name=""IsMetric""> " _
        & "<vt:bool>false</vt:bool>" _
        & "</property> " _
        & "<property fmtid=""{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"" pid=""6"" name=""TimeEdited""> " _
        & "<vt:filetime>2012-03-03T15:01:42Z</vt:filetime> " _
        & "</property> " _
        & "<property fmtid=""{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"" pid=""7"" name=""RecalcDocument""> " _
        & "<vt:bool>true</vt:bool> " _
        & "</property> " _
        & "</Properties>"

    '
    ' sample xml sequence for core.xml file
    '
    Public Const coreXML As String = "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes"" ?> " _
        & "<cp:coreProperties " _
        & "xmlns:cp=""http://schemas.openxmlformats.org/package/2006/metadata/core-properties"" " _
        & "xmlns:dc=""http://purl.org/dc/elements/1.1/"" " _
        & "xmlns:dcterms=""http://purl.org/dc/terms/"" " _
        & "xmlns:dcmitype=""http://purl.org/dc/dcmitype/"" " _
        & "xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> " _
        & "<dc:title/> " _
        & "<dc:subject/> " _
        & "<dc:creator>Administrator</dc:creator> " _
        & "<cp:keywords/> " _
        & "<dc:description/> " _
        & "<cp:lastModifiedBy>Administrator</cp:lastModifiedBy> " _
        & " <cp:lastPrinted>2012-03-03T15:01:42Z</cp:lastPrinted> " _
        & "<dcterms:created xsi:type=""dcterms:W3CDTF"">2012-03-03T15:01:42Z</dcterms:created> " _
        & "<dcterms:modified xsi:type=""dcterms:W3CDTF"">2012-03-03T15:02:21Z</dcterms:modified> " _
        & "<cp:category/> " _
        & "<dc:language>en-US</dc:language> " _
        & "</cp:coreProperties>"

    Public Const appXML As String = "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes"" ?>  " _
        & "<Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"" " _
        & "xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes""> " _
        & "<Template /> " _
        & "<Application>Microsoft Visio</Application> " _
        & "<ScaleCrop>false</ScaleCrop> " _
        & "<HeadingPairs> " _
        & "<vt:vector size=""2"" baseType=""variant""> " _
        & "<vt:variant> " _
        & "<vt:lpstr>Pages</vt:lpstr> " _
        & "</vt:variant> " _
        & "<vt:variant> " _
        & "<vt:i4>1</vt:i4> " _
        & "</vt:variant> " _
        & "</vt:vector> " _
        & "</HeadingPairs> " _
        & "<TitlesOfParts> " _
        & "<vt:vector size=""1"" baseType=""lpstr""> " _
        & "<vt:lpstr>Page-1</vt:lpstr> " _
        & "</vt:vector> " _
        & "</TitlesOfParts> " _
        & "<Manager /> " _
        & "<Company /> " _
        & "<LinksUpToDate>false</LinksUpToDate> " _
        & "<SharedDoc>false</SharedDoc> " _
        & "<HyperlinkBase /> " _
        & "<HyperlinksChanged>false</HyperlinksChanged> " _
        & "<AppVersion>15.0000</AppVersion> " _
        & "</Properties>"


    Public Const windowsXML As String = "<?xml version=""1.0"" encoding=""utf-8"" ?> " _
        & "<Windows ClientWidth=""983"" ClientHeight=""671"" xmlns=""http://schemas.microsoft.com/office/visio/2012/main"" " _
        & "xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" " _
        & "xml:space=""preserve""> " _
        & "<Window ID=""0"" WindowType=""Drawing"" WindowState=""1073741824"" WindowLeft=""-8"" WindowTop=""-30"" WindowWidth=""999"" " _
        & "WindowHeight=""709"" ContainerType=""Page"" Page=""0"" ViewScale=""-1"" ViewCenterX=""4.2592592592593"" ViewCenterY=""5.5277777777778""> " _
        & "<ShowRulers>1</ShowRulers> " _
        & "<ShowGrid>1</ShowGrid> " _
        & "<ShowPageBreaks>1</ShowPageBreaks> " _
        & "<ShowGuides>1</ShowGuides> " _
        & "<ShowConnectionPoints>1</ShowConnectionPoints> " _
        & "<GlueSettings>9</GlueSettings> " _
        & "<SnapSettings>65847</SnapSettings> " _
        & "<SnapExtensions>34</SnapExtensions> " _
        & "<SnapAngles/> " _
        & "<DynamicGridEnabled>0</DynamicGridEnabled> " _
        & "<TabSplitterPos>0.5</TabSplitterPos> " _
        & "</Window> " _
        & "</Windows>"

#End Region


#Region " Properties and Declarations "

    '
    ' this is the document package part
    '
    Public m_xDoc As XDocument
    Public Property xDoc As XDocument
        Get
            Return Me.m_xDoc
        End Get
        Set(value As XDocument)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "xDoc is Null.")
            End If
            Me.m_xDoc = value
        End Set
    End Property


    '
    '
    '
    Private m_fileCurrent As String
    Public Property fileCurrent As String
        Get
            fileCurrent = m_fileCurrent
        End Get
        Set(value As String)
            m_fileCurrent = value
            If ((value Is Nothing) Or (value = "")) Then
                Throw New System.ArgumentNullException("Value", _
                    "fileCurrent is Null.")
            End If
        End Set
    End Property

    '
    '
    '
    Public _visPackage As clsVisPackage
    Public Property visPackage As clsVisPackage
        Get
            visPackage = Me._visPackage
        End Get
        Set(value As clsVisPackage)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "visPackage is Null.")
            End If
            Me._visPackage = value
        End Set
    End Property

    '
    ' pkgpartInfo is the collection of content and file pointers in the package
    '
    Private m_colPkgPartInfo As Collection(Of pkgpartInfo)
    Public Property colPkgPartInfo As Collection(Of pkgpartInfo)
        Get
            colPkgPartInfo = m_colPkgPartInfo
        End Get
        Set(value As Collection(Of pkgpartInfo))
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "colPkgPartsInfo is Null.")
            End If
            m_colPkgPartInfo = value
        End Set
    End Property




#End Region





#Region " generic methods "

    '
    '
    '
    Public Function getDocumentPkgPart() _
        As XDocument

        Dim xdocReturn As XDocument = New XDocument
        Dim strTest As String = ""
        Try

            Dim strContent As String = ""
            Dim strpkgpartPath As String = ""
            Dim packagePath As String = Me.visPackage.fileCurrent

            For Each pkgpartInfo In Me.visPackage.colPkgPartInfo
                strContent = pkgpartInfo.pkgpartContentType
                ' use a generic search so we do not have to define all of the file types
                If strContent.Contains("vnd.ms-visio.drawing") Then
                    ' get the part xml file path
                    strpkgpartPath = pkgpartInfo.pkgpartPath
                    ' re-read the package
                    Using visPackage As Package = Package.Open(packagePath, FileMode.Open, FileAccess.Read)
                        Dim visPackageRelationship As PackageRelationship = _
                          visPackage _
                          .GetRelationshipsByType(clsVisPackage.relRidDocument) _
                          .FirstOrDefault()
                        If (visPackageRelationship IsNot Nothing) Then
                            Dim documentUri As Uri = _
                              PackUriHelper _
                              .ResolvePartUri(New Uri("/", UriKind.Relative), visPackageRelationship.TargetUri)
                            Dim documentPart As PackagePart = visPackage.GetPart(documentUri)
                            '  Load the document XML in the part into an XDocument instance.
                            xdocReturn = XDocument.Load(XmlReader.Create(documentPart.GetStream()))
                        End If

                        visPackage.Close()
                    End Using

                    GC.Collect()

                    ' all done
                    Exit For
                End If ' test for visio drawing 
            Next pkgpartInfo

        Catch xml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(xml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        Return xdocReturn

    End Function

    '
    '
    '
    Public Function getDocPkgPart(ByVal strPkgPart) As XDocument

        Dim xdocReturn As XDocument = New XDocument

        Select Case strPkgPart
            Case "app"
                strPkgPart = pkgVisio.clsVisPackage.contXmlApp
            Case "core"
                strPkgPart = pkgVisio.clsVisPackage.contXmlCore
            Case Else
                GoTo ExitFunction
        End Select

        Try


            Dim colPkgParts As Collection(Of pkgpartInfo) = New Collection(Of pkgpartInfo)
            colPkgParts.Clear()

            colPkgParts = Me.visPackage.getPkgPartsByContent(strPkgPart)
            If colPkgParts.Count = 1 _
                And Me.visPackage.colPkgPartInfo.Count <> 0 Then
                Dim pkgInfo As pkgpartInfo = colPkgParts(0)
                xdocReturn = Me.visPackage.getPackagePartAsXDoc(Me.visPackage.fileCurrent, pkgInfo)
            End If

        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

ExitFunction:
        Return xdocReturn

    End Function

    '
    ' events
    '
    Public Sub loadEvents(ByRef lvControl As ListView)


        Try

            Dim qryEvents = Me.xDoc...<EventItem>
            Dim intEvents As Integer = qryEvents.Count


            Dim lvItem As ListViewItem

            Dim lngId As ULong = 0
            Dim shtEventCode As UShort = 0
            Dim shtAction As UShort = 0
            Dim strTarget As String = ""
            Dim strTargetArgs As String = ""

            If lvControl IsNot Nothing Then
                lvControl.Items.Clear()
                lvControl.Columns.Clear()
                lvControl.View = View.Details
                lvControl.AllowColumnReorder = True
                lvControl.FullRowSelect = True

                lvControl.Columns.Add("Id", 50, HorizontalAlignment.Right)
                lvControl.Columns.Add("Action", 50, HorizontalAlignment.Left)
                lvControl.Columns.Add("Code", 50, HorizontalAlignment.Right)
                lvControl.Columns.Add("Target", 200, HorizontalAlignment.Left)
                lvControl.Columns.Add("TargArgs", 200, HorizontalAlignment.Left)
            End If


            For Each vevent In qryEvents

                Dim lngEventId As Long = -1

                Dim listOfAttributes As IEnumerable(Of XAttribute) = _
                    From att In vevent.Attributes() _
                    Select att
                For Each att As XAttribute In listOfAttributes
                    'Console.WriteLine("{0}={1}", att.Name.LocalName, att.Value)

                    Select Case LCase(att.Name.LocalName)
                        Case "id"
                            lngId = CLng(att.Value)
                        Case "eventcode"
                            shtEventCode = CShort(att.Value)
                        Case "action"
                            shtAction = CShort(att.Value)
                        Case "target"
                            strTarget = CStr(att.Value)
                        Case "targetargs"
                            strTargetArgs = CStr(att.Value)

                    End Select
                Next att

                If lvControl IsNot Nothing Then
                    lvItem = New ListViewItem(lngId)
                    lvItem.SubItems.Add(CStr(shtEventCode))
                    lvItem.SubItems.Add(CStr(shtAction))
                    lvItem.SubItems.Add(strTarget)
                    lvItem.SubItems.Add(strTargetArgs)

                    ' add it to the listview on the data page
                    lvControl.Items.Add(lvItem)
                End If

            Next vevent

        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    '
    '
    Public Sub CreateBlankDrawing _
        (ByVal packagePath As String, _
         ByVal strPageType As String)



        ' Create the Package
        ' (If the package file already exists, FileMode.Create will
        '  automatically delete it first before creating a new one.
        '  The 'using' statement insures that 'package' is
        '  closed and disposed when it goes out of scope.)

        Dim strRid As String = ""
        Const bufSize As Integer = &H1000
        Dim uniEncoding As New UTF8Encoding
        Dim byteXML As Byte()

        Try


            ' create the package
            '
            Using package As Package = package.Open(packagePath, FileMode.Create)



                '**********************************************
                ' Add the VisioDocument part to the Package from file in resources directory - rId1
                '**********************************************
                strRid = "rId1"
                ' Relative path and filename of the app file to add to the package.
                Dim visiodocPath As String = "/visio/document.xml"
                Dim partUriVisioDoc As Uri = PackUriHelper.CreatePartUri(New Uri(visiodocPath, UriKind.Relative))
                Dim packagePartVisioDoc As PackagePart = package.CreatePart(partUriVisioDoc, "application/vnd.ms-visio.drawing.main+xml")

                Using fileStream As New FileStream("resources\document.xml", FileMode.Open, FileAccess.Read)
                    Me.visPackage.CopyStream(fileStream, packagePartVisioDoc.GetStream())
                End Using 'Close and dispose fileStream.

                package.CreateRelationship(packagePartVisioDoc.Uri, TargetMode.Internal, clsVisPackage.relRidDocument, strRid)

                '**********************************************
                ' Add the Thumbnail part to the Package from file in resources directory - rId2
                '**********************************************
                strRid = "rId2"
                ' Relative path and filename of the app file to add to the package.
                Dim emfPath As String = "/docProps/thumbnail.emf"
                ' create the uri pointer
                Dim partUriEMF As Uri = PackUriHelper.CreatePartUri(New Uri(emfPath, UriKind.Relative))
                ' create the empty package part (also loads the content_type part)
                Dim packagePartEMF As PackagePart = package.CreatePart(partUriEMF, "image/x-emf")
                ' Copy the sample data to the Document Part from a file in the resources subdirectory of our project
                Using fileStream As New FileStream("resources\thumbnail.emf", FileMode.Open, FileAccess.Read)
                    Me.visPackage.CopyStream(fileStream, packagePartEMF.GetStream())
                End Using 'Close and dispose fileStream.
                Const PackageEmfRelationshipType As String = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"
                package.CreateRelationship(packagePartEMF.Uri, TargetMode.Internal, PackageEmfRelationshipType, strRid)

                '**********************************************
                ' Add the Core part to the Package - rid3
                '**********************************************
                strRid = "rId3"
                ' Relative path and filename of the core file to add to the package.
                Dim corePath As String = "/docProps/core.xml"
                Dim partUriCore As Uri = PackUriHelper.CreatePartUri(New Uri(corePath, UriKind.Relative))
                Dim packagePartCore As PackagePart = package.CreatePart(partUriCore, "application/vnd.openxmlformats-package.core-properties+xml")

                ' load the byte array string variable
                byteXML = uniEncoding.GetBytes(coreXML)
                Using memStream As New MemoryStream(bufSize)
                    memStream.Write(byteXML, 0, byteXML.Length)
                    Me.visPackage.CopyStream(memStream, packagePartCore.GetStream())
                End Using ' close the memory stream
                package.CreateRelationship(packagePartCore.Uri, TargetMode.Internal, clsVisPackage.relRidCore, strRid)

                '**********************************************
                ' Add the App part to the Package - rId4
                '**********************************************
                strRid = "rId4"
                ' Relative path and filename of the app file to add to the package.
                Dim appPath As String = "/docProps/app.xml"
                Dim partUriApp As Uri = PackUriHelper.CreatePartUri(New Uri(appPath, UriKind.Relative))
                Dim packagePartApp As PackagePart = package.CreatePart(partUriApp, "application/vnd.openxmlformats-officedocument.extended-properties+xml")

                ' load the byte array
                byteXML = uniEncoding.GetBytes(appXML)
                Using memStream As New MemoryStream(bufSize)
                    memStream.Write(byteXML, 0, byteXML.Length)
                    Me.visPackage.CopyStream(memStream, packagePartApp.GetStream())
                End Using ' close the memory stream
                package.CreateRelationship(packagePartApp.Uri, TargetMode.Internal, clsVisPackage.relRidExtended, strRid)

                '**********************************************
                ' Add the Custom part to the Package - rId5
                '**********************************************
                strRid = "rId5"
                ' Relative path and filename of the app file to add to the package.
                Dim customPath As String = "/docProps/custom.xml"
                Dim partUriCustom As Uri = PackUriHelper.CreatePartUri(New Uri(customPath, UriKind.Relative))
                Dim packagePartCustom As PackagePart = package.CreatePart(partUriCustom, "application/vnd.openxmlformats-officedocument.custom-properties+xml")

                ' load the byte array
                byteXML = uniEncoding.GetBytes(customXML)
                Using memStream As New MemoryStream(bufSize)
                    memStream.Write(byteXML, 0, byteXML.Length)
                    Me.visPackage.CopyStream(memStream, packagePartCustom.GetStream())
                End Using ' close the memory stream
                package.CreateRelationship(packagePartCustom.Uri, TargetMode.Internal, clsVisPackage.relRidCustom, strRid)


                '**********************************************
                ' Add the Windows part to the Package (visiodoc packagepart) - rId1
                '**********************************************
                strRid = "rId1"
                ' Relative path and filename of the app file to add to the package.
                Dim windowsPath As String = "/visio/windows.xml"
                Dim partUriWindows As Uri = PackUriHelper.CreatePartUri(New Uri(windowsPath, UriKind.Relative))
                Dim packagePartWindows As PackagePart = package.CreatePart(partUriWindows, "application/vnd.ms-visio.windows+xml")

                ' load the byte array
                byteXML = uniEncoding.GetBytes(windowsXML)
                Using memStream As New MemoryStream(bufSize)
                    memStream.Write(byteXML, 0, byteXML.Length)
                    Me.visPackage.CopyStream(memStream, packagePartWindows.GetStream())
                End Using ' close the memory stream
                packagePartVisioDoc.CreateRelationship(packagePartWindows.Uri, TargetMode.Internal, clsVisPackage.relRidWindows, strRid)

                '**********************************************
                ' Add the Pages part to the Package (visiodoc packagepart) - rId2
                '**********************************************
                strRid = "rId2"
                ' Relative path and filename of the app file to add to the package.
                Dim pagesPath As String = "/visio/pages/pages.xml"
                Dim partUriPages As Uri = PackUriHelper.CreatePartUri(New Uri(pagesPath, UriKind.Relative))
                Dim packagePartPages As PackagePart = package.CreatePart(partUriPages, clsVisPackage.contXmlPages)

                ' load the byte array
                byteXML = uniEncoding.GetBytes(clsPages.pagesHeaderXML)
                Using memStream As New MemoryStream(bufSize)
                    memStream.Write(byteXML, 0, byteXML.Length)
                    Me.visPackage.CopyStream(memStream, packagePartPages.GetStream())
                End Using ' close the memory stream
                packagePartVisioDoc.CreateRelationship(packagePartPages.Uri, TargetMode.Internal, clsVisPackage.relRidPages, strRid)

                '**********************************************
                ' Add the Masters part to the Package (visiodoc packagepart) - rId2
                '**********************************************
                strRid = "rId3"
                ' Relative path and filename of the app file to add to the package.
                Dim mastersPath As String = "/visio/masters/masters.xml"
                Dim partUriMasters As Uri = PackUriHelper.CreatePartUri(New Uri(mastersPath, UriKind.Relative))
                Dim packagePartMasters As PackagePart = package.CreatePart(partUriMasters, clsVisPackage.contXmlMasters)

                ' load the byte array
                byteXML = uniEncoding.GetBytes(clsMasters.MastersHeaderXML)
                Using memStream As New MemoryStream(bufSize)
                    memStream.Write(byteXML, 0, byteXML.Length)
                    Me.visPackage.CopyStream(memStream, packagePartMasters.GetStream())
                End Using ' close the memory stream
                packagePartVisioDoc.CreateRelationship(packagePartMasters.Uri, TargetMode.Internal, clsVisPackage.relRidMasters, strRid)


                package.Close()

            End Using 'Close and update package.

        Catch xml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(xml, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        GC.Collect()


        ' finished the basics now add the first page

        addPageToDocument(packagePath, strPageType, 0, "Page-1", "Page1.xml", "rId1")

    End Sub


    '
    '
    '
    Public Sub addPageToDocument(ByVal packagePath As String, _
                                 Optional ByVal strPageType As String = "portrait", _
                                 Optional ByVal intPageId As Integer = 0, _
                                 Optional ByVal strPageNameU As String = "Page-1", _
                                 Optional ByVal strPageXml As String = "Page1.xml", _
                                 Optional ByVal strRelId As String = "rId1")


        Try

            '
            ' open the package and add a pages pkgpart and a page pkgpart
            '
            Using package As Package = package.Open(packagePath, FileMode.Open, FileAccess.ReadWrite)

                Dim visPages As clsPages = New clsPages
                If strPageType = "portrait" Then
                    ' the default behaviour of this is to add the first page with a rId1 relationship
                    visPages.addPortraitPageToPagesPkgPart(package, CStr(intPageId), strPageNameU, strPageXml, strRelId)
                Else
                    visPages.addLandscapePageToPackage(package, CStr(intPageId), strPageNameU, strPageXml, strRelId)
                End If

                ' go find the pages packagepart.
                Dim pagesPath As String = "/visio/pages/pages.xml"
                Dim partUriPages As Uri = PackUriHelper.CreatePartUri(New Uri(pagesPath, UriKind.Relative))
                Dim pkgpartPages As PackagePart = package.GetPart(New Uri(pagesPath, UriKind.Relative))

                '**********************************************
                ' Add the page1 part to the Package (pages packagepart) - rId1
                '**********************************************
                Dim visPage As clsPage = New clsPage
                visPage.visPackage = Me.visPackage
                visPage.addPageToPkgPart(package, pkgpartPages, strPageXml, strRelId)

                visPages = Nothing
                visPage = Nothing
                package.Close()

            End Using

            GC.Collect()

        Catch xml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(xml, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub



#End Region





    '
    '
    '
    Public Sub New()


        Me._visPackage = Nothing
        Me.visPackage = New clsVisPackage
        Me.m_colPkgPartInfo = Nothing
        Me.colPkgPartInfo = New Collection(Of pkgpartInfo)
        Me.m_xDoc = Nothing
        Me.xDoc = New XDocument





    End Sub




    Protected Overrides Sub Finalize()

        If Me.m_colPkgPartInfo IsNot Nothing Then
            m_colPkgPartInfo = Nothing
        End If

        If Me.m_xDoc IsNot Nothing Then
            Me.m_xDoc = Nothing
        End If

        GC.Collect()
        GC.Collect()


        MyBase.Finalize()
    End Sub
End Class
